#!/usr/bin/python
# coding=utf-8

import os
import sys
import shutil
import json

argv_len = 0

jarsigner_path = r'jarsigner.exe'
apktool_path = r'"'+sys.path[0]+'/apktool.bat'+'"'
keystore_path = r'"'+sys.path[0]+'/private_data/android_0.keystore'+'"'

private_data = json.loads(open(sys.path[0]+"/private_data/base.json").read())
keystore_alias = private_data["keystore_alias"]
storepass = private_data["keystore_storepass"]
keypass = private_data["keystore_keypass"]

bale_command = apktool_path+' %s %s %s %s'
sign_command = jarsigner_path+' -keystore %s -storepass %s -keypass %s -signedjar %s %s %s'

def main():
    do = sys.argv[1]
    x1 = ""
    if argv_len >= 3 and sys.argv[2]:
        x1 = sys.path[0]+'/'+sys.argv[2]
    x2 = ""
    if argv_len >= 4 and sys.argv[3]:
        x2 = sys.path[0]+'/'+sys.argv[3]
    apktool_ops = "-f"
    if argv_len >= 5 and sys.argv[4]:
        apktool_ops = sys.argv[3]
    if do == 'bs':
        #加签名
        command = bale_command % ('b', apktool_ops, x1, x2)
        os.system(command)
        input_jar = ''
        output_jar = ''
        if x2 == '':
            input_jar = x1+'.apk'
            output_jar = x1+'_release.apk'
        else:
            input_jar = x2
            pos = x2.rfind('.')
            if pos != -1:
                output_jar = x2[0:pos]+'_release.apk'
        #print('java -jar signapk.jar testkey.x509.pem testkey.pk8 %s %s' % (input_jar, output_jar))
        #os.system('java -jar signapk.jar testkey.x509.pem testkey.pk8 %s %s' % (input_jar, output_jar))
        command = sign_command % (keystore_path, storepass, keypass, output_jar, input_jar, keystore_alias)
        print(command)
        os.system(command)
        if os.path.isfile(input_jar):
            os.remove(input_jar)
    else:
        command = bale_command % (do, apktool_ops, x1, x2)
        print(command)
        os.system(command)
    print ('ok')

if __name__ == '__main__':
#    print sys.argv
    argv_len = len(sys.argv)
    if argv_len >= 2 and sys.argv[1] == '-h':
        print ("Usage:bale.py d|b|bs xfile|xdir xdir|xfile [ops]")
        exit(1)
    if argv_len < 3:
        print ('Usage:bale.py d|b|bs xfile|xdir xdir|xfile [apktool_ops]')
        exit(1)
#    if not (os.path.isdir(sys.argv[1])):
#        print ('argv[1] nees is dir.')
#        exit(1)
    main()
